import discord

class Player(object):
    """youmu's voice module"""
    def __init__(self, bot):
        self.bot = bot
        self._voice = None
        self._ytplayer = None
        if not discord.opus.is_loaded():
            discord.opus.load_opus()

    # creates voice
    async def create_voice(self, channel):
        self._voice = await self.bot.join_voice_channel(channel)

    # joins the callers voice channel
    async def join(self, message):
        try:
            await self.create_voice(message.author.voice_channel)
            await self.bot.send_message(message.channel, "On my way!")
        except discord.ClientException:
            await self.bot.send_message(message.channel, "Already in a voice channel...")
        except discord.InvalidArgument:
            await self.bot.send_message(message.channel, "This is not a voice channel...")

    # follows the callers channel
    async def follow(self, message):
        await self.bot.send_message(message.channel, "On my way!")
        await self.voice.move_to(message.author.voice_channel)

    # starts playing audio of specified video (complete url or video id), stops previous ._ytplayer if called again while playing
    async def play(self, message, command):
        if "https://www.youtube.com/watch?" not in command.split(' ')[1]:
            yt = "https://www.youtube.com/watch?v=" + command.split(' ')[1]
        else:
            yt = command.split(' ')[1]
        if self._ytplayer != None:
            if self._ytplayer.is_playing():
                self._ytplayer.stop()
        self._ytplayer = await self.voice.create_ytdl_player(yt)
        self._ytplayer.start()
        await self.bot.send_message(message.channel, "Okay! Will play " + self._ytplayer.title + " in " + message.author.voice_channel.name)

    # sets volume of currently playing song
    async def volume(self, message, command):
        if self._ytplayer != None:
            if self._ytplayer.is_playing():
                player.volume = int(command.split(' ')[1]) / 100
                await self.bot.send_message(message.channel, "Set the volume to {:.0%}".format(player.volume))

    # pauses from playing current player
    async def pause(self, message):
        self._ytplayer.pause()
        await self.bot.send_message(message.channel, "Alright.")

    # resumes playing current player
    async def resume(self, message):
        self._ytplayer.resume()
        await self.bot.send_message(message.channel, "Okay!")

    # stops playing current player
    async def stop(self, message):
        self.player.stop()
        await self.bot.send_message(message.channel, "Alright. :pensive: ")

    # disconnects from current voice channel (voice => 0)
    async def exit(self, message):
        await self.bot.send_message(message.channel, "Bye Bye!")
        await self.voice.disconnect()
